const jwt = require('jsonwebtoken')
const config = require('./config')

const allows = [
  {path:'/users/$', method:'PUT'},
  {path:'/users/login$', method:'POST'},
  {path:'/users/exits$', method:'POST'},
  {path:'/users/$', method:'GET'},
  {path:'/articles/[0-9]{0,8}$', method:'GET'},
  {path:'/articles/lastest/[0-9]{0,8}$', method:'GET'}
]

module.exports = async function(ctx, next){
  var filtered = allows.filter((value) => new RegExp(value.path).test(ctx.path) && ctx.method === value.method)
  console.log(filtered);
  if(filtered.length !==0 ){
    await next()
    return
  }

  var auth = ctx.headers['authorization']
  if(!auth)
    ctx.throw(403, 'No Authorization head.')
    try {
      var user = jwt.verify(auth,config.secretKey)
    } catch (e) {
      ctx.throw(403, 'Invalid token.')
    }
    console.log(user)
    ctx.currentUser = user
    await next()
}
